package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.example.demo.config.property.SecurityProperties;
import com.example.demo.exception.ServiceException;
import com.example.demo.log.Log;
import com.example.demo.log.LogModuleEnum;
import com.example.demo.model.core.R;
import com.example.demo.model.core.ResultCode;
import com.example.demo.security.model.AuthenticationToken;
import com.example.demo.security.model.CaptchaInfo;
import com.example.demo.service.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/auth")
@Tag(name = "认证接口")
public class SysAuthController {

    final static String REFRESH_TOKEN_COOKIE_NAME = "refreshToken";

    @Autowired
    private AuthService authService;
    @Autowired
    private SecurityProperties securityProperties;

    @GetMapping("/captcha")
    @Operation(summary = "获取验证码")
    public R<CaptchaInfo> getCaptcha() {
        CaptchaInfo captcha = authService.getCaptcha();
        return R.ok(captcha);
    }

    @PostMapping("/login")
    @Operation(summary = "登录")
    @Log(value = "登录--账号密码登录", module = LogModuleEnum.LOGIN)
    public R<AuthenticationToken> login(
            @Parameter(description = "用户名", example = "admin") @RequestParam String username,
            @Parameter(description = "密码", example = "123456") @RequestParam String password, HttpServletRequest request, HttpServletResponse response) {
        AuthenticationToken authenticationToken = authService.login(username, password);
        addRefreshTokenCookie(response, authenticationToken);
        authenticationToken.setRefreshToken(null);
        return R.ok(authenticationToken);
    }

    @PostMapping("/logout")
    @Operation(summary = "登出")
    public R<Void> logout(HttpServletRequest request, HttpServletResponse response) {
        // 删除cookie
        removeRefreshTokenCookie(request, response);
        authService.logout();
        return R.ok();
    }

    @PostMapping("/refreshToken")
    @Operation(summary = "刷新Token")
    public R<AuthenticationToken> refreshToken(HttpServletRequest request, HttpServletResponse response) {
        String refrshTokenStr = getRefreshTokenCookie(request);
        if (StrUtil.isBlank(refrshTokenStr)) {
            throw new ServiceException(ResultCode.REFRESH_TOKEN_INVALID);
        }
        AuthenticationToken authenticationToken = authService.refreshToken(refrshTokenStr);
        if (authenticationToken == null) {
            throw new ServiceException(ResultCode.REFRESH_TOKEN_INVALID);
        }

        addRefreshTokenCookie(response, authenticationToken);
        authenticationToken.setRefreshToken(null);
        return R.ok(authenticationToken);
    }

    private void addRefreshTokenCookie(HttpServletResponse response, AuthenticationToken authenticationToken) {
        Cookie cookie = new Cookie(REFRESH_TOKEN_COOKIE_NAME, authenticationToken.getRefreshToken());
        cookie.setHttpOnly(true);
        cookie.setMaxAge(securityProperties.getSession().getRefreshTokenTimeToLive());
        cookie.setSecure(true);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    private void removeRefreshTokenCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (REFRESH_TOKEN_COOKIE_NAME.equals(cookie.getName())) {
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                    return;
                }
            }
        }
    }

    private String getRefreshTokenCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (REFRESH_TOKEN_COOKIE_NAME.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

}
